package com.lanou.dllo.vc.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou.dllo.vc.R;
import com.lanou.dllo.vc.activity.AddActivity;
import com.lanou.dllo.vc.activity.AddFriendMessage;
import com.lanou.dllo.vc.activity.ChatActivity;
import com.lanou.dllo.vc.activity.GroupChatActivity;
import com.lanou.dllo.vc.adapter.TelAdapter;
import com.lanou.dllo.vc.entity.User;
import com.lanou.dllo.vc.entity.UserEntity;
import com.lanou.dllo.vc.util.CharacterParser;
import com.lanou.dllo.vc.view.ContactItemView;
import com.lanou.dllo.vc.view.EaseSidebar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;



/**
 * Created by dllo on 15/11/23.
 */
public class AddressFragment extends Fragment {
    private ListView list;
    private ImageView addIv;
    private ContactItemView contactItemView, group_item;
    private TextView friend;
    private String usernameString = null , reasonString;
    private List<String> username;
//    private ArrayAdapter<String> adapter;

    private EaseSidebar sidebar;
    private TelAdapter telAdapter;
    // private CharacterParser characterParser;
    private UserEntity user;
    private List<UserEntity> users;
    private TextView textView_dialog;

    private static int NOTITY = 1;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==NOTITY) {
                telAdapter.notifyDataSetChanged();
            }
            return false;
        }
    });


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }


    /**
     * 在这个方法里面，获取传入的数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    /**
     * 这个方法里面加载布局
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.ease_fragment_contact_list, null);

        return view;
    }


    /**
     * 控件初始化在这写
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        View v = View.inflate(getContext(), R.layout.em_contacts_header, null);
        sidebar = (EaseSidebar) view.findViewById(R.id.sidebar);
        textView_dialog = (TextView) view.findViewById(R.id.textView_dialog);
        sidebar.setTextView(textView_dialog);
        telAdapter = new TelAdapter(getContext(), R.layout.row_contact);
        list = (ListView) view.findViewById(R.id.friends_listView);

        list.addHeaderView(v);
        list.setAdapter(telAdapter);

        user = new UserEntity();
        users = new ArrayList<>();
        addIv = (ImageView) view.findViewById(R.id.addIv);
        addIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(getActivity(), AddActivity.class);
                        startActivity(intent);
                    }
                }).start();
            }
        });
        contactItemView = (ContactItemView) view.findViewById(R.id.application_item);
        contactItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddFriendMessage.class);
                Log.i("lanou","----usernameString--->>>"+usernameString);
                if (usernameString != null && usernameString.length() > 0) {
                    intent.putExtra("username", usernameString);
                }

                startActivity(intent);
            }
        });
        friend = (TextView) view.findViewById(R.id.friend);

        group_item = (ContactItemView) view.findViewById(R.id.group_item);
        group_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GroupChatActivity.class);
                if (usernameString != null && usernameString.length() > 0) {
                    intent.putExtra("username", usernameString);
                }

                startActivity(intent);
            }
        });
        sidebar.setOnLetterClickedListener(new EaseSidebar.OnLetterClickedListener() {
            @Override
            public void onLetterClicked(String str) {
                int position = telAdapter.getPositionForSection(str
                        .charAt(0));
                list.setSelection(position);
            }
        });
    }


    /**
     * 数据初始化在这写
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EMChat.getInstance().setAppInited();

        EMChatManager.getInstance().getChatOptions().setUseRoster(true);


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    username = EMContactManager.getInstance().getContactUserNames();
                    for (int i = 0; i < username.size(); i++) {
                        UserEntity userEntity = new UserEntity();
                        String user_name = username.get(i);
                        String head = CharacterParser.getInstance().getPinyin(user_name);
                        String firstLetter = head.substring(0, 1).toUpperCase();

                        if (firstLetter.matches("[A-Z]")) {
                            Log.i("qqq","1头部"+firstLetter);
                            userEntity.setHeader(firstLetter);
                        } else {
                            Log.i("qqq","头部"+firstLetter);
                            userEntity.setHeader("#");
                        }
                        userEntity.setUsername(user_name);
                        users.add(userEntity);
                    }

                    Log.i("qqq", users + "+++++");



//                    list.setAdapter(adapter);
                    Message message = new Message();
                    message.what = NOTITY;
                    handler.sendEmptyMessage(message.what);



                    Collections.sort(users, new Comparator<UserEntity>() {
                        @Override
                        public int compare(UserEntity lhs, UserEntity rhs) {
                            if (lhs.getHeader().equals("#")) {
                                return 1;
                            } else if (rhs.getHeader().equals("#")) {
                                return -1;
                            } else {
                                return lhs.getHeader().compareTo(rhs.getHeader());
                            }
                        }
                    });

                    telAdapter.addData(users);
                    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(getActivity(), ChatActivity.class);
                            String name = username.get(position - 1);
                            intent.putExtra("name", name);
                            startActivity(intent);
                        }
                    });
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }

            }


        }).start();


        EMContactManager.getInstance().setContactListener(new EMContactListener() {
            @Override
            public void onContactAdded(List<String> lists) {

                Log.i("lanou", "------------>花花大傻子2" + list);
                if (lists != null) {
                    //    adapter = new ArrayAdapter<String>(getContext(), R.layout.tab_friend_item, username);
//                    adapter.add(lists.get(0));
//                    telAdapter.addData(lists);

                    for (String s : lists) {
                        Log.i("lanou00", "--------->" + s);
                        String head = CharacterParser.getInstance().getPinyin(s);
                        String firstLetter = head.substring(0, 1).toUpperCase();
                        user.setUsername(s);
                        if (firstLetter.matches("[A-Z]")) {
//                            userModel.setFirstLetter(firstLetter);

                            user.setHeader(firstLetter);
                        } else {
                            user.setHeader("#");
                        }
                        users.add(user);

                    }


                    telAdapter.addData(users);
                }


                // telAdapter.notifyDataSetChanged();

                Log.i("lanou","----------->"+Thread.currentThread());
                telAdapter.notifyDataSetChanged();



            }

            @Override
            public void onContactDeleted(List<String> list) {
                Log.i("lanou", "------------>花花大傻子1");
            }

            @Override
            public void onContactInvited(String username, String reason) {
                //收到好友邀请
                Log.i("lanou", "------------>花花大傻子" + username + "--" + reason);

                usernameString = username;
                reasonString = reason;

            }

            @Override
            public void onContactAgreed(String s) {
                Log.i("lanou", "------------>花花大傻子3");
            }

            @Override
            public void onContactRefused(String s) {
                Log.i("lanou", "------------>花花大傻子4");
            }
        });


    }


}
